package com.emotion.sshticket.utilitys;

public class PagingUtil {
	public static String getPaging(int page, int pageRange, int totalCount, int listLimit) {
		int maxPage = 1;
		if (listLimit > 0 && totalCount > listLimit) {
			maxPage = totalCount / listLimit;
		}

		int start = page - (pageRange / 2);
		if (start < 1) {
			start = 1;
		}
		int end = start + pageRange - 1;
		if (end > maxPage) {
			end = maxPage;
		}

		StringBuffer sb = new StringBuffer();
		if (page > (pageRange / 2) + 1) {
			sb.append("<a href=" + getScriptUrl(1) + ">[처음]</a>");
		}
		if (start > pageRange) {
			sb.append("<a href=" + getScriptUrl(start - 1) + ">[이전]</a>");
		}

		for (int idx = start; idx <= end; idx++) {
			if (idx == page) {
				sb.append("<strong>[" + idx + "]</strong>");
			} else {
				sb.append("<a href=" + getScriptUrl(idx) + ">[" + idx + "]</a>");
			}
		}

		if (end < (maxPage - pageRange)) {
			sb.append("<a href=" + getScriptUrl(end + 1) + ">[다음]</a>");
			sb.append("<a href=" + getScriptUrl(maxPage) + ">[마지막]</a>");
		}

		return sb.toString();
	}

	private static String getScriptUrl(int index) {
		return "javascript:goPage(" + index + ");";
	}

	public static String getPaging(String url, int page, int pageRange, int totalCount, int listLimit) {
		int maxPage = 1;
		if (listLimit > 0 && totalCount > listLimit) {
			maxPage = totalCount / listLimit;
		}

		int start = page - (pageRange / 2);
		if (start < 1) {
			start = 1;
		}
		int end = start + pageRange - 1;
		if (end > maxPage) {
			end = maxPage;
		}

		if (url.indexOf("?") > -1) {
			if (url.charAt(url.length() - 1) != '&') {
				url = url + "&";
			}
			url = url + "page=";
		} else {
			url = url + "?page=";
		}

		StringBuffer sb = new StringBuffer();
		if (page > (pageRange / 2) + 1) {
			sb.append("<a href=" + url + "1" + ">[처음]</a>");
		}
		if (start > pageRange) {
			sb.append("<a href=" + url + (start - 1) + ">[이전]</a>");
		}

		for (int idx = start; idx <= end; idx++) {
			if (idx == page) {
				sb.append("<strong>[" + idx + "]</strong>");
			} else {
				sb.append("<a href=" + url + idx + ">[" + idx + "]</a>");
			}
		}

		if (end < (maxPage - pageRange)) {
			sb.append("<a href=" + url + (end + 1) + ">[다음]</a>");
			sb.append("<a href=" + url + maxPage + ">[마지막]</a>");
		}

		return sb.toString();
	}
}
